package com.ys.peony.ui.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.ys.peony.R;
import com.ys.peony.app.AppManager;
import com.ys.peony.app.HttpURL;
import com.ys.peony.app.YSConstant;
import com.ys.peony.base.BaseActivity;
import com.ys.peony.http.JCHttpManagerUtils;
import com.ys.peony.http.base.BaseRespCallBack;
import com.ys.peony.model.UserModel;
import com.ys.peony.services.ServerPushService;
import com.ys.peony.ui.fragment.HomeFragment;
import com.ys.peony.ui.fragment.MineFragment;
import com.ys.peony.ui.fragment.ReportFragment;
import com.ys.peony.utils.JSONUtil;
import com.ys.peony.utils.LogUtil;
import com.ys.peony.utils.PermissionUtils;
import com.ys.peony.utils.SharePreferencesUtils;
import com.ys.peony.utils.ToastUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;

/**
 * describe:首页
 * author:zhangcong
 * date:2017/5/26 15:29
 */
public class MainActivity extends BaseActivity implements ServiceConnection {

    private final static String TAG = "MainActivity";

    @BindView(R.id.bottom_rg_menu)
    RadioGroup mRadioGroup;

    @BindView(R.id.bottom_rb_home)
    RadioButton bottom_home;

    @BindView(R.id.bottom_rb_data)
    RadioButton bottom_data;

    @BindView(R.id.bottom_rb_my)
    RadioButton bottom_my;

    @BindView(R.id.view_pager)
    ViewPager mViewPager;

    private ServerPushService pushService;

    private List<Fragment> mFragmentList;
    private Fragment mFragment[] = {new HomeFragment(), new ReportFragment(), new MineFragment()};
    private Timer mTimer = null;//用户登录保活定时

    @Override
    protected int getContentResId() {
        return R.layout.activity_main;
    }

    @Override
    public void initView() {
        initData();
        initEvent();
        setAdapt();
        //6.0以上版本需要主动申请权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            PermissionUtils.checkAndRequestPermissions(this);
        }
        //绑定websocket服务
        Intent intent = new Intent(MainActivity.this, ServerPushService.class);
        bindService(intent, this, Context.BIND_AUTO_CREATE);

        setUserInfoActive();
    }

    private void initData() {
        mFragmentList = new ArrayList<Fragment>();
        for (int i = 0; i < mFragment.length; i++) {
            mFragmentList.add(mFragment[i]);
        }
    }

    private void initEvent() {
        mRadioGroup.setOnCheckedChangeListener(new MyOnCheckedChangeListener());
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                changeBtn(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void setAdapt() {
        mViewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return mFragmentList.get(position);
            }

            @Override
            public int getCount() {
                return mFragmentList.size();
            }
        });
    }


    @Override
    protected void onDestroy() {
        //解绑服务
        unbindService(this);
        stopTimer();
        super.onDestroy();
    }


    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        if (pushService == null) {
            pushService = ((ServerPushService.LocalBinder) service).getService();
        }
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {

    }

    private long preTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            if (System.currentTimeMillis() - preTime < 2000) {
                //退出程序
                AppManager.getAppManager().AppExit(this);
            } else {
                preTime = System.currentTimeMillis();
                ToastUtils.showToast(this, "再次点击，退出应用");
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void changeBtn(int position) {
        switch (position) {
            case 0:
                bottom_home.setChecked(true);
                break;
            case 1:
                bottom_data.setChecked(true);
                break;
            case 2:
                bottom_my.setChecked(true);
                break;
        }
    }

    private class MyOnCheckedChangeListener implements RadioGroup.OnCheckedChangeListener {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId) {
                case R.id.bottom_rb_home:
                    mViewPager.setCurrentItem(0);
                    break;
                case R.id.bottom_rb_data:
                    mViewPager.setCurrentItem(1);
                    break;
                case R.id.bottom_rb_my:
                    mViewPager.setCurrentItem(2);
                    break;
            }
        }
    }

    /**
     * 描述:设置用户保活
     */
    private void setUserInfoActive() {
        // 初始化定时器
        stopTimer();
        mTimer = new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                Log.d(TAG, "设置用户保活");
                doUserValid();
            }
        }, 0, YSConstant.TIME_25);
    }

    // 停止定时器
    private void stopTimer() {
        if (mTimer != null) {
            mTimer.cancel();
            // 一定设置为null，否则定时器不会被回收
            mTimer = null;
        }
    }

    /**
     * 描述:当前用户登录超过30分钟需要请求接口保活
     *
     * @return
     */
    public void doUserValid() {
        final JCHttpManagerUtils httpManagerUtils = new JCHttpManagerUtils();
        Map<String, Object> params = new HashMap<String, Object>();
        String pwd = SharePreferencesUtils.getInstance().getValueByKey(YSConstant.SP_PWD);
        String userName = SharePreferencesUtils.getInstance().getUserModel().getAccount();
        if (TextUtils.isEmpty(userName) || TextUtils.isEmpty(pwd)) {
            skipToTargetPage(LoginActivity.class, null);
            return;
        }
        params.put("username", userName);
        params.put("password", pwd);
        httpManagerUtils.get(HttpURL.login, params, new BaseRespCallBack(null) {
            public void onRespSuccess(String respStr) {
                SharePreferencesUtils.getInstance().setKeyValue(YSConstant.USER_INFO, respStr);
                SharePreferencesUtils.getInstance().setUserModel(JSONUtil.parseObject(respStr, UserModel.class));
                LogUtil.i(TAG, "用户长连接 success" + respStr);
            }

            @Override
            public void onRespFailure(String msg) {
                super.onRespFailure(msg);
                LogUtil.i(TAG, "用户长连接 fail" + msg);
            }
        });
    }

}
